package com.momalib.ning2_nocode.utils;

import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class XmlUtil {

    public static String convertDocumentToString(Document doc) {
        try {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            // 设置输出属性以格式化XML
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

//            DOMSource source = new DOMSource(doc);
//            StringWriter writer = new StringWriter();
//            StreamResult result = new StreamResult(writer);
//
//            transformer.transform(source, result);
//            return writer.toString();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            StreamResult result = new StreamResult(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
            transformer.transform(new DOMSource(doc), result);

            return outputStream.toString(StandardCharsets.UTF_8).replace("\r\n", "\n");
        } catch (Exception e) {
            throw new RuntimeException("Error converting Document to String: " + e.getMessage(), e);
        }
    }

    public static String convertDocumentToString2(Document document) {
        DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
        LSSerializer serializer = domImplLS.createLSSerializer();
        // 获取 DOMConfiguration 并设置编码参数
        DOMConfiguration config = serializer.getDomConfig();
        if (config.canSetParameter("encoding", "UTF-8")) {
            config.setParameter("encoding", "UTF-8");
        }
        if (config.canSetParameter("format-pretty-print", Boolean.TRUE)) {
            config.setParameter("format-pretty-print", Boolean.TRUE);
        }
        return serializer.writeToString(document).replaceFirst("encoding=\"UTF-16\"", "encoding=\"UTF-8\"");
    }

    public static Node convertTextToNode(Document target, String xmlStr) {
        DocumentBuilderFactory factory2 = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder2 = null;
        try {
            builder2 = factory2.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        }
        Document sourceDoc = null;
        try {
            sourceDoc = builder2.parse(new InputSource(new StringReader(xmlStr)));
        } catch (SAXException | IOException e) {
            throw new RuntimeException(e);
        }
        Node nodeToInsert = sourceDoc.getDocumentElement(); // 获取要插入的根节点

        // 将解析出的节点导入到目标文档中
        return target.importNode(nodeToInsert, true);
    }
}
